package com.wanmait.hotelManage.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.wanmait.hotelManage.dao.AdminDAO;
import com.wanmait.hotelManage.vo.Admin;

/**
 * Servlet implementation class AdminServlet
 */
@WebServlet("/manage/AdminServlet")
public class AdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	request.setCharacterEncoding("UTF-8");
		String action=request.getParameter("action");
	if("login".equals(action)) {
		this.login(request, response);
	}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
//	protected void updateinit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		HttpSession session=request.getSession();
//		Admin admin=(Admin)session.getAttribute("admin");
//		request.setAttribute("admin", admin);
//		request.getRequestDispatcher("/manage/update.jsp").forward(request, response);
//	}
	/**
	 * 登录
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String code=request.getParameter("code");
		HttpSession session=request.getSession();
		String codeimg=(String)session.getAttribute("code");
		if(code==null||!code.equalsIgnoreCase(codeimg)) {
			response.sendRedirect(request.getContextPath()+"/manage/login.jsp");
			return;
	}
		
		String username=request.getParameter("username");
		String password=request.getParameter("pwd");
		Admin admin=AdminDAO.getAdmindao().finduserNameandPassword(username,password);
		if(admin==null) {
			response.sendRedirect(request.getContextPath()+"/manage/login.jsp?mag=login1");
			return;
		}
		if(admin!=null) {
			session.setAttribute("admin", admin);
			String url2 = (String)session.getAttribute("goUrl2");
			System.out.println(url2);
			if(url2==null||"http://localhost:8080/hotelManage/manage/login.jsp".equals(url2)) {
				response.sendRedirect(request.getContextPath()+"/manage/index.jsp");
			}else {
				response.sendRedirect(url2.toString());
			}
		}
	}
}
